Skip to content

Exercises

Click the ball

Let's build a simple game!

In the playground below, a ball moves around randomly. The goal of the game is to click the ball. We want to show an alert when the ball is successfully clicked:

We can use window.alert() to show the message.

Acceptance Criteria:

  • When the user clicks the ball, a winning message should be shown.
  • You should handle “click” events specifically, as this event is triggered on click, on tap, and even when the user focuses the element with the keyboard and hits the “Enter” key.
    • If you don't use a pointer device, you can use the keyboard method to test your code.

NOTE: If you find the ball movement distracting, you can disable it. Pop over to the CSS tab and comment out the first chunk of CSS.

Code Playground

import React from 'react';

import VisuallyHidden from './VisuallyHidden';

function ClickBallGame() {
return (
<div className="wrapper">
<button
className="ball"
>
<VisuallyHidden>
Ball
</VisuallyHidden>
</button>
</div>
);
}

export default ClickBallGame;

Solution:

Click the ball v2

Let's make our game a bit more interesting.

In addition to the ball, it now features a bomb. If the bomb is clicked, we want to show a "lose" message:

Below, you'll find a mostly-complete implementation, but there's a problem. Clicking either item—bomb or ball—shows the “lose” message.

Your mission is to fix the code below so that it shows the right message depending on which item is clicked.

Acceptance Criteria:

  • When the user clicks the ball, a winning message should be shown.
  • When the user clicks the bomb, a losing message should be shown.
  • The handleClick function should still be used, and you shouldn't have to change anything about the function itself.

Once again, you can comment out the first chunk of CSS to disable the movement.

Code Playground

import React from 'react';

import VisuallyHidden from './VisuallyHidden';

function ClickBallGame() {
function handleClick(type) {
if (type === 'win') {
alert('You win!');
} else {
alert('You lose :(');
}
}
return (
<div className="wrapper">
<button
className="ball"
onClick={handleClick}
>
<VisuallyHidden>
Ball
</VisuallyHidden>
</button>
<button
className="bomb"
onClick={handleClick}
>
<span
role="img"
aria-label="bomb"
>
💣
</span>
</button>
</div>
);
}

export default ClickBallGame;

Solution: